#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QDebug>
#include <sys/socket.h>
#include <unistd.h>
#include <QMessageBox>

ClientWidget::ClientWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ClientWidget)
{
    ui->setupUi(this);
    m_clientThread = new QThread(this);
    m_client = new Client;
    m_client->moveToThread(m_clientThread);
    m_clientThread->start();

    connect(this, &ClientWidget::startClient, m_client, &Client::connectToServer);
    connect(m_client, &Client::connectStatus, this, [=](int status){
        if (status > 0)
        {
            m_clientFd = status;
            qDebug() << "connect to server successed.";
        }
        else
        {
            qDebug() << "connect to server failed.";
            QMessageBox::information(this, QString::fromLocal8Bit("警告"),QString::fromLocal8Bit("连接失败！"));
            emit startClient();
        }
    });
    connect(this, &ClientWidget::sendFilename, m_client, &Client::sendFilenameToServer);
    connect(m_client, &Client::diliverHtmlToMain, this, &ClientWidget::showWebpage);


    emit startClient();
}

ClientWidget::~ClientWidget()
{
    delete ui;
    shutdown(m_clientFd, SHUT_RD);
    ::close(m_clientFd);
    qDebug() << "close socket: " << m_clientFd;
    m_clientThread->quit();
    m_clientThread->wait();
    qDebug() << "client Thread closed successed.";
    m_client->deleteLater();

}

void ClientWidget::showWebpage(QString html)
{
    if (html.startsWith('1'))
    {
        ui->showBox->insertHtml(html.right(html.size() - 1));

    }
    else
    {
        QMessageBox::information(this, QString::fromLocal8Bit("警告"),QString::fromLocal8Bit("文件打开失败！"));
    }
}


void ClientWidget::on_submitBtn_clicked()
{
    QString filename = ui->urlRequest->text();
    ui->urlRequest->clear();
    ui->showBox->clear();
    emit sendFilename(filename);
}

